<template>
  <transition name="fade-opacity">
    <div
      v-show="showSelectRecommend"
      class="c-bg-white my-modal-page c-flex-column c-maxw640 c-p-l0 c-p-r0 c-m-0auto"
    >
      <div class="c-w100 c-ph24">
        <my-small-tabbar
          id="tabhBar"
          :fontSet="{defaultColor:'c-fc-sblack', activeColor:'c-fw500'}"
          :tabList="tabList"
          :tabIndex="typeBar"
          @changeTab="changeType"
          class="c-bg-white"
        ></my-small-tabbar>
      </div>
      <new-search-bar
        :placeholder="'请输入搜索内容'"
        @search="startSearch"
        @cancel="startSearch"
      ></new-search-bar>
      <div
        @scroll="onScrollEvent"
        id="souceScroll"
        class="c-bg-white c-ph24 c-pb100 c-flex-grow1 c-h0 c-contexty-scroll"
      >
        <div
          class="c-flex-row c-bd-b1 c-pv24"
          v-for="(item, index) in sourceList"
          :key="index"
          @click.stop="handleClickSelect(item)"
        >
          <div class="c-flex-row c-flex-center c-hh120">
            <i
              class="iconfont c-fs24"
              :class="item.isCheck ?'theme-fc':'c-fc-sgray'"
            >{{item.isCheck ? `&#xe871;`:`&#xe872;`}}</i>
          </div>
          <!-- 左边图片 -->
          <div
            class="c-ww180 c-hh120 c-br12 c-ml24 c-p"
            v-if="typeBar == 1"
          >
            <img
              class="c-w100 c-h c-object-fit-cover c-br12"
              :src="$addXossFilter(item.avatar, require('@/assets/defult270.png'))"
              alt=""
            >
            <div class="c-pa c-p-b0 c-p-r0 c-ph8 c-hh26 c-fs18 c-fc-white c-translucent-balck50 c-br-tl12 c-br-br12 c-flex-row c-flex-center">{{item.type == 0 ?'视频':item.type == 1?'音频':'图文'}}</div>
          </div>
          <div
            class="c-ww180 c-hh120 c-br12 c-ml24 c-p"
            v-else-if="typeBar == 4"
          >
            <img
              class="c-w100 c-h c-object-fit-cover c-br12"
              :src="$addXossFilter(item.avatar, require('@/assets/defult270.png'))"
              alt=""
            >
            <div
              class="c-pa c-p-b0 c-p-r0 c-ph8 c-hh26 c-fs18 c-fc-white c-translucent-balck50 c-br-tl12 c-br-br12 c-flex-row c-flex-center"
              v-if="item.isUpdating == 1"
            >更新中...</div>
          </div>
          <div
            class="c-ww180 c-hh120 c-br12 c-ml24 c-p"
            v-else-if="typeBar == 5 || typeBar == 6 || typeBar == 7 || typeBar == 8"
          >
            <img
              class="c-w100 c-h c-object-fit-cover c-br12"
              :src="$addXossFilter(item.avatar, require('@/assets/defult270.png'))"
              alt=""
            >
          </div>
          <!-- 右边描述 -->
          <div
            v-if="typeBar == 1"
            class="c-flex-grow1 c-w0 c-flex-column c-hh120 c-justify-sb c-ml20"
          >
            <div class="c-fs24 c-fc-xblack c-text-ellipsis2">{{item.name}}</div>
            <div class="c-flex-row c-justify-sb c-aligni-center">
              <div
                v-if="item.isSaleOnly == 1"
                class="theme-fc c-fs24"
              >
                <span v-if="item.payType == 2">{{'￥' | iosPriceFilter}}</span>
                {{item.payType | priceValueFilter(item.price, 5)}}
              </div>
              <div class="c-fs18">
                <i class="iconfont c-fs18 c-fc-gray">&#xe7a8;</i> {{item.lecturer || ''}}
              </div>
            </div>
          </div>
          <div
            v-else-if="typeBar == 4"
            class="c-flex-grow1 c-w0 c-flex-column c-hh120 c-justify-sb c-ml20"
          >
            <div class="c-fs24 c-fc-xblack c-text-ellipsis2">{{item.name}}</div>
            <div class="c-flex-row c-justify-sb c-aligni-center">
              <div class="theme-fc c-fs24">
                <span v-if="item.payType == 2">{{'￥' | iosPriceFilter}}</span>
                {{item.payType | priceValueFilter(item.price, 9)}}
              </div>
              <div class="c-fs18 c-fc-gray">暂含{{item.hasCourse || 0}}课</div>
            </div>
          </div>
          <div
            v-else-if="typeBar == 5"
            class="c-flex-grow1 c-w0 c-flex-column c-hh120 c-justify-sb c-ml20"
          >
            <div class="c-fs24 c-fc-xblack c-text-ellipsis2">{{item.name}}</div>
            <div class="c-flex-row c-justify-sb c-aligni-center">
              <div class="theme-fc c-fs24">
                <span v-if="item.payType == 2">{{'￥' | iosPriceFilter}}</span>
                {{item.payType | priceValueFilter(item.price, 11)}}
              </div>
              <div class="c-fs18 c-fc-gray">考试{{item.hasCourse || 0}}套</div>
            </div>
          </div>
          <div
            v-else-if="typeBar == 6"
            class="c-flex-grow1 c-w0 c-flex-column c-hh120 c-justify-sb c-ml20"
          >
            <div class="c-fs24 c-fc-xblack c-text-ellipsis1">{{item.name}}</div>
            <div
              class="c-fs18 c-fc-gray c-text-ellipsis1"
              v-if="item.city"
            >{{item.city}}</div>
            <div class="c-flex-row c-justify-sb c-aligni-center">
              <span class="theme-fc c-fs24">{{item.price.split('~')[0]==item.price.split('~')[1] && item.price.split('~')[0] * 1 == 0 ? '免费': item.price.split('~')[0]==item.price.split('~')[1] ?
                `${item.price.split('~')[0]}`:`${item.price.split('~')[0]}起`}}</span>
              <div class="c-fs18 c-fc-gray">{{item.startAt}}</div>
            </div>
          </div>
          <div
            v-else-if="typeBar == 7"
            class="c-flex-grow1 c-w0 c-flex-column c-hh120 c-justify-sb c-ml20"
          >
            <div class="c-fs24 c-fc-xblack c-text-ellipsis2">{{item.name}}</div>
            <div class="c-flex-row c-justify-sb c-aligni-center">
              <div class="theme-fc c-fs24">
                <span v-if="item.price * 1 > 0">{{'￥' | iosPriceFilter}}</span>
                {{item.payType | priceValueFilter(item.price, 41)}}
              </div>
              <div class="c-fs18 c-fc-gray">{{item.type == 1 ? '日历打卡':item.type == 2 ?'作业打卡':'闯关打卡'}}</div>
            </div>
          </div>
          <div
            v-else-if="typeBar == 8"
            class="c-flex-grow1 c-w0 c-flex-column c-hh120 c-justify-sb c-ml20"
          >
            <div class="c-fs24 c-fc-xblack c-text-ellipsis2">{{item.name}}</div>
            <div class="c-flex-row c-justify-sb c-aligni-center">
              <div class="theme-fc c-fs24">
                <span>{{'￥' | iosPriceFilter}}{{item.price}}</span>
                <span
                  v-if="item.originalPrice * 1 > 0"
                  class="c-fs24 c-fc-gray c-text-decoration-through c-ml12"
                >{{'￥' | iosPriceFilter}}{{item.originalPrice}}</span>
              </div>
            </div>
          </div>
        </div>
        <loading-status-tem
          :dataStatus="dataStatus"
          noDataText="暂无内容"
        ></loading-status-tem>
      </div>
      <!-- 底部 -->
      <div class="c-pa c-p-b0 c-maxw640 c-w100 c-hh108 c-bg-white c-flex-row c-justify-sb c-aligni-center c-ph24 bottom_btn_group">
        <div
          class="c-ww284 c-hh60 c-bd1 c-bg-white c-flex-row c-flex-center c-fs24 c-fc-xblack c-br30"
          @click="closeSelectRecommendModal"
        >取消</div>
        <div
          class="c-ww284 c-hh60 theme-bg c-flex-row c-flex-center c-fs24 c-fc-white c-br30"
          @click="handleClickSelectRecommendModal"
        >确定</div>
      </div>
    </div>
  </transition>
</template>

<script>
import { mapMutations, mapState } from 'vuex';
import { utilJs } from "@/utils/common.js";
import newSearchBar from "@/components/templates/common/newSearchBar.vue";
import MySmallTabbar from "@/components/templates/common/MySmallTabbar.vue";
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
const LIMIT = 10;
let pageIndex = 1;
export default {
  name: 'CircleSelectRecommend',
  props: {
    showSelectRecommend: {
      type: Boolean,
      default: false
    }
  },
  components: {
    newSearchBar,
    MySmallTabbar,
    loadingStatusTem
  },
  watch: {
    showSelectRecommend(val) {
      if (val) {
        this.initData()
      }
    }
  },
  data() {
    return {
      searchText: '',
      typeBar: 1,
      tabList: [],
      sourceList: [],
      dataStatus: 'HAS_MORE_DATA',
      companyAuth: null,
      selectRecommendList: [],
    }
  },
  computed: {
    ...mapState({
      circleRecommendList: state => state.circle.circleRecommendList
    })
  },
  mounted() {
    this.companyAuth = localStorage.getItem("companyAuth") && JSON.parse(localStorage.getItem("companyAuth"));
    let columnAuth = this.companyAuth && this.companyAuth.enableColumnModule;
    let examAuth = this.companyAuth && this.companyAuth.enableExamModule;
    let activityAuth = this.companyAuth && this.companyAuth.enableActivityModule;
    let clockAuth = this.companyAuth && this.companyAuth.enableSignCardModule;
    let shopAuth = this.companyAuth && this.companyAuth.enableMallModule;
    let sourceArr = [{
      title: '课程',
      index: 1,
    }];
    columnAuth && sourceArr.push({
      title: '专栏',
      index: 4,
    });
    if (!this.$isStore()) {
      examAuth && sourceArr.push({
        title: '测评',
        index: 5,
      });
    }
    activityAuth && sourceArr.push({
      title: '活动',
      index: 6,
    });
    clockAuth && sourceArr.push({
      title: '打卡',
      index: 7,
    });
    shopAuth && sourceArr.push({
      title: '商城',
      index: 8,
    })
    this.tabList = sourceArr;
  },
  methods: {
    ...mapMutations({
      updateCircleRecommendList: "circle/updateCircleRecommendList"
    }),
    initData() {
      this.typeBar = 1;
      pageIndex = 1;
      this.dataStatus = 'HAS_MORE_DATA';
      this.searchText = '';
      this.sourceList = [];
      this.selectRecommendList = JSON.parse(JSON.stringify(this.circleRecommendList))
      this.getSourceList()
    },
    handleClickSelectRecommendModal() {
      console.log(this.selectRecommendList)
      this.updateCircleRecommendList(this.selectRecommendList)
      this.$emit('handleClickSelectRecommendModal')
    },
    closeSelectRecommendModal() {
      this.$emit('closeSelectRecommendModal')
    },
    getSourceList() {
      if (this.dataStatus == 'LOADING') {
        return;
      }
      this.dataStatus = 'LOADING';
      utilJs.getMethod(`${global.apiurl}social/getResourceList?name=${this.searchText}&type=${this.typeBar}&page=${pageIndex}&limit=${LIMIT}`, res => {
        if (pageIndex == 1) {
          this.sourceList = res.data || [];
        } else {
          this.sourceList = [...this.sourceList, ...res.data];
        }
        // 循环给数据绑上是否选中类型
        this.sourceList.map(item => {
          this.$set(item, 'isCheck', false)
          this.$set(item, 'typeBar', this.typeBar)
        })
        // 循环的时候需要判断存储的值去比较然后绑定已经选中的内容
        this.comparisonArray(this.sourceList, this.selectRecommendList)
        if (res.data && (res.data.length < LIMIT)) {
          this.dataStatus = pageIndex == 1 && res.data.length == 0 ? 'NO_DATA' : 'NO_MORE_DATA'
        } else {
          this.dataStatus = 'HAS_MORE_DATA'
          pageIndex++;
        }
      });
    },
    onScrollEvent(e) {
      let domModal = document.getElementById('souceScroll');
      if (this.dataStatus == 'HAS_MORE_DATA' && domModal.scrollTop + domModal.clientHeight > domModal.scrollHeight - 100) {
        this.getSourceList();
      }
    },
    // 两个数组比较
    comparisonArray(arr1, arr2) {
      arr1.filter(item => arr2.some(ele => {
        if (ele.rId == item.rId) {
          console.log('存在相同数据')
          this.$set(item, 'isCheck', true)
        }
      }))
    },
    handleClickSelect(item) {
      if (this.selectRecommendList.length >= 5 && item.isCheck == false) {
        this.$showCjToast({
          text: '最多只能选择5条',
          type: "warn",
        })
        return
      }
      this.sourceList.forEach(element => {
        if (element.rId === item.rId) {
          element.isCheck = !element.isCheck
          // 首先先判断是否存在存储数据当中
          const index = this.selectRecommendList.findIndex(item => item.rId === element.rId)
          if (index === -1) {
            console.log('不存在')
            const obj = element
            this.selectRecommendList.push(obj)
          } else {
            console.log('存在')
            // 若存在，则判断当前是选中还是取消选中
            if (!element.isCheck) {
              this.selectRecommendList = this.removeArray(this.selectRecommendList, element.rId)
              console.log(this.removeArray(this.selectRecommendList, element.rId))
              // this.selectRecommendList = this.selectRecommendList.splice(this.selectRecommendList.findIndex(item => item.rId == element.rId), 1)
            }
          }
        }
      });
    },
    // 过滤方法
    removeArray(arr, item) {
      return arr.filter((value) => {
        return value.rId != item
      })
    },
    startSearch(e) {
      pageIndex = 1;
      this.searchText = e.searchValue
      this.getSourceList();
    },
    changeType(type) {
      if (this.typeBar == type) {
        return;
      }
      this.typeBar = type;
      pageIndex = 1;
      this.sourceList = [];
      this.getSourceList();
    }
  }
}
</script>

<style lang="less" scoped>
.my-modal-page {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 2018;
  width: 100%;
  height: 100%;
  background-color: #ffffff;
}
.fixTop {
  position: fixed;
  z-index: 100;
  transform: translateZ(0);
  -webkit-transform: translateZ(0);
  left: 0;
  right: 0;
  max-width: 16rem;
  margin: 0 auto;
}
.bottom_btn_group {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.1);
}
</style>